<template>
  <div class="quality-config">
    <div class="models">
      <el-button
        icon="el-icon-plus"
        size="mini"
        @click="createModel"
        v-functions="['qc_webchat_session_config_create']"
        >新建模板</el-button
      >
      <div
        v-if="models && models.length"
        class="all-models"
        ref="models"
        v-on:scroll="getMoreModels($event)"
      >
        <div
          class="model-name"
          :class="{
            active: item.choose,
          }"
          v-for="(item, index) in models"
          :key="index"
          @click="chooseModel(item)"
        >
          <el-tooltip effect="dark" :content="item.name" placement="top">
            <span class="name">{{ item.name }}</span>
          </el-tooltip>
          <span>
            <i
              class="V7_iconfont V7_iconV7tubiao_xianbianji"
              v-functions="['qc_webchat_session_config_modify']"
              @click="editModel(item)"
            ></i>
            <i
              class="V7_iconfont V7_iconV7tubiao_shanchu"
              v-functions="['qc_webchat_session_config_delete']"
              @click="delModel(item)"
            ></i>
          </span>
        </div>
      </div>
      <div v-else class="no-data">暂无数据</div>
    </div>
    <ConfigDetail
      :data="chooseModelData"
      @updateConfigModels="updateConfigModels"
    />
    <MoveDialog
      :visible.sync="createShow"
      :before-close="closeDialog"
      class="formRef"
      width="400px"
      :close-on-click-modal="false"
      append-to-body
    >
      <template slot="title">
        <span>新建模板</span>
      </template>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input
            v-model="formData.name"
            clearable
            placeholder="请输入模板名称"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            :rows="4"
            v-model="formData.description"
            clearable
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit" size="mini">确 定</el-button>
        <el-button @click="closeDialog" size="mini">取 消</el-button>
      </div>
    </MoveDialog>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import configTable from '@/components/globalTool/resizeTable/index.vue'
import MoveDialog from '@/components/globalTool/moveDialog/index.vue'
import draggable from 'vuedraggable'
import ConfigDetail from './configDetail.vue'
import { commonAction, deepClone } from '@/utils/common'
@Component({
  name: 'wechatConfig',
  components: {
    configTable,
    MoveDialog,
    draggable,
    ConfigDetail
  }
})
export default class QualityLog extends Vue {
  [x: string]: any
  @Ref() private readonly formRef: any

  private models: any = []

  private chooseModelData: any = {}

  private createShow: boolean = false

  private formData: any = {}

  private statusType: any = ''

  private firstShow: boolean = true // 初始化默认选中第一个模板

  private pageData: any = {
    page: 1,
    limit: 20
  }

  private allShow: boolean = false

  private rules: any = {
    name: [
      { required: true, trigger: 'blur', message: '请输入模板名称' }
    ]
  }

  private chooseModel (item: any) {
    this.models.forEach(v => { // 选中的模板添加class:active
      if (v._id === item._id) {
        this.$set(v, 'choose', true)
      } else {
        this.$set(v, 'choose', false)
      }
    })
    this.chooseModelData = item
  }

  private delModel (row: any) {
    this.$confirm('删除此模板与配置，请确认是否要删除', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const params = {
        url: '/im-center/action/qualityConfig/delete',
        method: 'POST',
        data: {
          _id: row._id
        }
      }
      commonAction(params).then(res => {
        if (res.success) {
          this.$message.success('删除成功')
          this.firstShow = true
          this.initConfig()
        }
      })
    })
  }

  private editModel (row: any) {
    this.statusType = 'edit'
    this.formData = deepClone(row)
    this.createShow = true
  }

  private submit () {
    this.formRef.validate(valid => {
      if (valid) {
        const params = {
          url: this.statusType === 'add' ? '/im-center/action/qualityConfig/add' : '/im-center/action/qualityConfig/update',
          method: 'POST',
          data: {
            name: this.formData.name,
            description: this.formData.description,
            _id: this.statusType === 'edit' ? this.formData._id : ''
          }
        }
        commonAction(params).then(res => {
          if (res.success) {
            this.createShow = false
            this.$message.success(`${this.statusType === 'add' ? '创建' : '修改'}成功`)
            this.initConfig(true)
          }
        })
      }
    })
  }

  private getConfig (update?: boolean) {
    const params = {
      url: '/im-center/action/qualityConfig/query',
      method: 'POST',
      data: {
        page: this.pageData.page,
        limit: this.pageData.limit
      }
    }
    commonAction(params).then(res => {
      if (res.success && res.data) {
        if (res.data && res.data.length) {
          this.models = this.models.concat(res.data)
          if (res.data.length < this.pageData.limit) {
            this.allShow = true
          } else {
            this.allShow = false
          }
          if (update) { // 配置更新后左侧选中样式
            this.chooseModel(this.chooseModelData)
          }
          if (this.firstShow) { // 初始化选中第一个
            this.chooseModel(res.data[0])
            this.firstShow = false
          }
        }
      }
    })
  }

  private initConfig (update?: boolean) {
    this.models = []
    this.pageData.page = 1
    this.getConfig(update)
  }

  private loadMore () {
    this.pageData.page++
    this.getConfig()
  }

  private getMoreModels (e) {
    const scrollTop = e.target.scrollTop
    const scrollHeight = e.target.scrollHeight
    const offsetHeight = Math.ceil(e.target.getBoundingClientRect().height)
    const currentHeight = scrollTop + offsetHeight
    if (currentHeight >= scrollHeight && !this.allShow) {
      this.loadMore()
    }
  }

  private async updateConfigModels () {
    this.initConfig(true)
  }

  private createModel () {
    this.statusType = 'add'
    this.formData = { // 清空数据
      name: '',
      description: ''
    }
    this.createShow = true
  }

  private closeDialog () {
    this.createShow = false
  }

  private created () {
    this.initConfig()
  }
}
</script>
<style lang="stylus" scoped>
.quality-config
  height 100%
  border 1px solid $border-main
  box-shadow 0px 0px 4px 0px #e0e6f0,0px 1px 4px 0px #e0e6f0
  border-radius 10px
  overflow hidden
  display flex
  .models
    width 210px
    border-right 1px solid #EBEFF3
    .el-button
      color #008bee
      margin 20px
    .no-data
      width 100%
      text-align center
      color #999
      margin-top 30px
    .all-models
      height calc(100% - 80px)
      overflow-y auto
      .model-name
        height 40px
        padding 14px 12px 14px 20px
        color #303753
        display flex
        justify-content space-between
        cursor pointer
        .name
          width 100%
          overflow hidden
          text-overflow ellipsis
          white-space nowrap
        i
          color #B3B9C7
          font-size 12px
          margin-left 12px
        &:hover
          background #F3FAFF
        &.active
          background #F3FAFF
.dialog-footer
  text-align right
</style>
